package com.gq.dungsihesman;


import java.util.ArrayList;
import java.util.Hashtable;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.gq.tab.scr.ImageDetailSrc;
import com.gq.utils.CustomViewPager;
import com.rtst.widget.tab.SwipeyTabs;
import com.rtst.widget.tab.SwipeyTabsAdapter;

public class ImageDetailActivity extends FragmentActivity {
	private SwipeyTabs mTabs;
	private CustomViewPager mViewPager;
	private String[] TITLES;
	private ArrayList<String> data;
	private SwipeyTabsPagerAdapter adapter;
	private AdView adView;
	private String[] pagesName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getIntent().getExtras();
		this.data = bundle.getStringArrayList("IMAGES");
		TITLES = new String[data.size()];
		pagesName = new String[data.size()];
		for (int i = 0; i < data.size(); i ++) {
			TITLES[i] = "" + (i + 1) + "/" + data.size();
			pagesName[i] = "Trang " + (i + 1);
		}
		int chapter = bundle.getInt("CHAPTER");
		setContentView(R.layout.activity_custom_swipeytab);
		adView = (AdView) findViewById(R.id.adView);
		AdRequest adRequest = new AdRequest();
		adView.loadAd(adRequest);
		mViewPager = (CustomViewPager) findViewById(R.id.viewpager);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		adapter = new SwipeyTabsPagerAdapter(this, getSupportFragmentManager());
		mViewPager = (CustomViewPager) findViewById(R.id.viewpager);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		mViewPager.setAdapter(adapter);
		mTabs.setAdapter(adapter);
//		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				mTabs.onPageSelected(position);
				adView.loadAd(new AdRequest());
			}
			
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				mTabs.onPageScrolled(position, positionOffset, positionOffsetPixels);
			}
			
			@Override
			public void onPageScrollStateChanged(int state) {
				mTabs.onPageScrollStateChanged(state);
			}
		});
		mViewPager.setCurrentItem(0);
		mViewPager.forceDisablePaging();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.read, menu);

		// Calling super after populating the menu is necessary here to ensure
		// that the
		// action bar helpers have a chance to handle this event.
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		
		switch (item.getItemId()) {
			case R.id.menu_firstpage:
				mViewPager.setCurrentItem(0); break;
			
			case R.id.menu_goto:
				AlertDialog.Builder builder = new Builder(this);
				builder.setInverseBackgroundForced(true);
				builder.setItems(pagesName, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (which != mViewPager.getCurrentItem()) {
							((SwipeyTabsPagerAdapter) mViewPager.getAdapter()).disposeAll();
							mViewPager.setCurrentItem(which);
						}
						dialog.dismiss();
					}
				});
				builder.create().show();
				break;
				
			case R.id.menu_lastpage:
				mViewPager.setCurrentItem(data.size()-1); break;
		}
		
		return super.onMenuItemSelected(featureId, item);
	}
	
	private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements SwipeyTabsAdapter {
		private final Context mContext;
//		private ImageDetailSrc[] views = new ImageDetailSrc[data.size()];
//		private LinkedList<ImageDetailSrc> views = new LinkedList<ImageDetailSrc>();
		private Hashtable<Integer, ImageDetailSrc> views = new Hashtable<Integer, ImageDetailSrc>();
		private boolean[] disposed = new boolean[data.size()];
		
		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
			super(fm);
			this.mContext = context;
		}
		
		@Override
		public Fragment getItem(int position) {
			ImageDetailSrc item = null;
			try {
				 item = views.get(position);
			} catch(IndexOutOfBoundsException e) {
				e.printStackTrace();
			}
			if (item == null) {
				String url = data.get(position);
				item = new ImageDetailSrc(url, mViewPager, mTabs);
				views.put(position, item);
			}
			return item;
		}
		
		@Override
		public int getCount() {
			return TITLES.length;
		}
		
		public ViewGroup getTab(final int position, SwipeyTabs root) {
			ViewGroup layout = (ViewGroup) LayoutInflater.from(mContext)
					.inflate(R.layout.swipey_tab_indicator, root, false);
		
			TextView view = (TextView) layout.findViewById(R.id.swipey_tab);
			view.setText(TITLES[position]);
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mViewPager.setCurrentItem(position);
				}
			});
			return layout;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			if (disposed[position] == true) {
				views.get(position).getImageViewPager().getImageView().prepareDownload(data.get(position));
				disposed[position] = false;
			}
			return super.instantiateItem(container, position);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			ImageDetailSrc item = views.get(position);
			if (item != null) {
				item.dispose();
				disposed[position] = true;
			}
		}
		
		public void disposeAll() {
			for(int i=0;i<views.size();i++) {
				try {
					ImageDetailSrc item = views.get(i);
					if (item != null) item.dispose();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			views.clear();
		}
	}

	@Override
	protected void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		adapter.disposeAll();
		super.onDestroy();
	}
	
}
